﻿namespace star_questionnair.Services.impl;

using MailKit.Net.Smtp;
using MimeKit;
using Microsoft.Extensions.Configuration;
using System.Threading.Tasks;

public class EmailService
{
    private readonly IConfiguration _configuration;

    public EmailService(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    // 发送简单邮件的方法
    public async Task SendSimpleMessageAsync(string username, string to, string subject, string text)
    {
        var message = new MimeMessage();
        message.From.Add(new MailboxAddress("星问卷", "1786480231@qq.com")); // 设置发件人邮箱和名称
        message.To.Add(new MailboxAddress(username, to)); // 收件人邮箱
        message.Subject = subject;

        message.Body = new TextPart("plain")
        {
            Text = text
        };

        await SendEmailAsync(message);
    }

    // 发送指定发件人、收件人、主题和内容的邮件
    public async Task SendEmailAsync(string from, string to, string subject, string text)
    {
        var message = new MimeMessage();
        message.From.Add(new MailboxAddress("星问卷", from)); // 设置发件人邮箱和名称
        message.To.Add(new MailboxAddress("", to)); // 收件人邮箱
        message.Subject = subject;

        message.Body = new TextPart("plain")
        {
            Text = text
        };

        await SendEmailAsync(message);
    }

    // 封装发送邮件的底层逻辑
    private async Task SendEmailAsync(MimeMessage message)
    {
        using (var smtpClient = new SmtpClient())
        {
            try
            {
                var smtpServer = _configuration["EmailSettings:Host"];
                var smtpPort = int.Parse(_configuration["EmailSettings:Port"]);
                var smtpUsername = _configuration["EmailSettings:Username"];
                var smtpPassword = _configuration["EmailSettings:Password"];

                // 连接到邮件服务器
                await smtpClient.ConnectAsync(smtpServer, smtpPort, true);
                await smtpClient.AuthenticateAsync(smtpUsername, smtpPassword);

                // 发送邮件
                await smtpClient.SendAsync(message);
                await smtpClient.DisconnectAsync(true);
            }
            catch (Exception ex)
            {
                // 处理错误
                throw new InvalidOperationException($"An error occurred while sending email: {ex.Message}", ex);
            }
        }
    }
}